<template>
  <div ref="chartRef" style="width: 100%; height: 300px;"></div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  realData: {
    type: Array,
    required: true
  }
})

const chartRef = ref(null)
let chart = null

const initChart = () => {
  const option = {
    title: {
      text: '土壤指标分析',
      textStyle: {
        color: '#eaeaea',
        fontSize: 14
      },
      left: 20
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        color: '#eaeaea'
      }
    },
    series: [
      {
        name: '土壤指标',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: [
          { value: props.realData[0], name: 'PH值' },
          { value: props.realData[1], name: '含氮量' },
          { value: props.realData[2], name: '温度' },
          { value: props.realData[3], name: '湿度' },
          { value: props.realData[4], name: '电导率' }
        ]
      }
    ]
  }

  if (chart) {
    chart.setOption(option)
  } else {
    chart = echarts.init(chartRef.value)
    chart.setOption(option)
  }
}

watch(() => props.realData, () => {
  initChart()
}, { deep: true })

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})
</script> 